//
//  CLGlobleDataModel.m
//  chanlin
//
//  Created by Ryan on 14-11-22.
//  Copyright (c) 2014年 chanlin. All rights reserved.
//

#import "CLGlobleDataModel.h"
#import "UMSocialData.h"
#import "UMSocialDataService.h"
#import "UMSocialSnsPlatformManager.h"
#import "UMSocialControllerService.h"
#import "UMessage.h"
#import "UMSocialSinaHandler.h"




@implementation CLGlobleDataModel


SGR_DEF_SINGLETION(CLGlobleDataModel)

- (instancetype)init{
    self=[super init];
    if(self){
        self.isSinaBind=[[NSUserDefaults standardUserDefaults] boolForKey:@"isSinaBind"];
        self.isNotPush=[[NSUserDefaults standardUserDefaults] boolForKey:@"isNotPush"];
    }
    return self;
}


- (void)setIsNotPush:(BOOL)isNotPush{
    _isNotPush=isNotPush;
    [[NSUserDefaults standardUserDefaults] setBool:isNotPush forKey:@"isNotPush"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

-(UIImage *)scaleShareThumbImage:(UIImage *)image toScale:(float)scaleSize

{
    float scale = 0.8;
    if (scaleSize<scale) {
        scale=scale<0.3?scaleSize:0.3;
    }
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scale, image.size.height * scale));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scale, image.size.height * scale)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return scaledImage;
    
}



- (void)share2Wechat:(UIImage *)icon
                title:(NSString *)title
              content:(NSString *)content
                  url:(NSString *)url
         captureImg:(UIImage *)img
              uiBlock:(void (^)(BOOL success,NSString *message) )block{
 
    self.block=block;
    if(img){
        WXMediaMessage *message = [WXMediaMessage message];
        UIImage *thuImg = [self scaleShareThumbImage:img toScale:(1.0*GlobleHeight/img.size.height)];
        [message setThumbImage:thuImg];
        
        // 封装的图片对象
        WXImageObject *imgObj = [WXImageObject object];
        NSData *imageData = UIImageJPEGRepresentation(img, 1.0);
        
        UIImage *img = [UIImage imageWithData:imageData];
        NSUInteger imagelen = [imageData length]/1024.0;
        if (imagelen/31.0>3){
            imageData = UIImageJPEGRepresentation(img, 0.0);
        }
        
        // 原大图
        imgObj.imageData = imageData;
        
        message.mediaObject = imgObj;
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
        req.bText = NO;
        req.message = message;
        req.scene = WXSceneSession;
        [WXApi sendReq:req];
    }else if(_isStrNotNull(url)){
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = title;
        message.description = content;
        [message setThumbImage:icon];
        
        WXWebpageObject *webObj = [WXWebpageObject object];
        webObj.webpageUrl = url;
        
        message.mediaObject = webObj;
        
        SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
        req.bText = NO;
        req.message = message;
        req.scene = WXSceneSession;
        
        [WXApi sendReq:req];
    }else{
        SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
        req.bText = YES;
        req.text = content;
        req.scene = WXSceneSession;
        
        [WXApi sendReq:req];

    }
    
    
    
    
}

- (void)shareMessage:(int )type content:(NSString *)content{
    switch (type) {
        case 1:
            [self share2Wechat:nil title:nil content:content url:nil captureImg:nil uiBlock:^(BOOL success, NSString *message) {
                
            }];
            break;
        case 2:
            [self share2pengyou:nil title:nil content:content url:nil captureImg:nil uiBlock:^(BOOL success, NSString *message) {
                
            }];
            break;
        case 3:
            [self share2Sina:content url:nil controller:(UIViewController *)[self k_currentController] captureImage:nil uiBlock:nil];
            break;
            
        case 4:
            [self share2QQ:nil title:nil content:content url:nil captureImage:nil thumbImg:nil uiBlock:^(BOOL success, NSString *message) {
                
            }];
            break;
            
        default:
            break;
    }
}

- (void)share2pengyou:(UIImage *)icon
                title:(NSString *)title
              content:(NSString *)content
                  url:(NSString *)url
           captureImg:(UIImage *)img
              uiBlock:(void (^)(BOOL success,NSString *message) )block{
    
    self.block=block;
    
    if(img){
        WXMediaMessage *message = [WXMediaMessage message];
        UIImage *thuImg = [self scaleShareThumbImage:img toScale:(1.0*GlobleHeight/img.size.height)];
        [message setThumbImage:thuImg];
        
        // 封装的图片对象
        WXImageObject *imgObj = [WXImageObject object];
        NSData *imageData = UIImageJPEGRepresentation(img, 1.0);
        
        UIImage *img = [UIImage imageWithData:imageData];
        NSUInteger imagelen = [imageData length]/1024.0;
        if (imagelen/31.0>3){
            imageData = UIImageJPEGRepresentation(img, 0.0);
        }
        
        // 原大图
        imgObj.imageData = imageData;
        
        message.mediaObject = imgObj;
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
        req.bText = NO;
        req.message = message;
        req.scene = WXSceneSession;
        [WXApi sendReq:req];
    }else if(_isStrNotNull(url)){
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = title;
        message.description = content;
        [message setThumbImage:icon];
        
        WXWebpageObject *webObj = [WXWebpageObject object];
        webObj.webpageUrl = url;
        
        message.mediaObject = webObj;
        
        SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
        req.bText = NO;
        req.message = message;
        req.scene = WXSceneTimeline;
        
        [WXApi sendReq:req];
    }else{
        SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
        req.bText = YES;
        req.text = content;
        req.scene = WXSceneTimeline;
        
        [WXApi sendReq:req];

    }
    
  
    
}

- (void)registQQ{
    
}

- (void)share2QQ:(UIImage *)icon
                title:(NSString *)title
              content:(NSString *)content
                  url:(NSString *)url
         captureImage:(UIImage *)captureImage
             thumbImg:(UIImage *)thumbImg
              uiBlock:(void (^)(BOOL success,NSString *message) )block{
    //self.block=block;
    
    
  
    __weak typeof(self) me=self;
    if(_isStrNotNull(url))
    [UMSocialData defaultData].extConfig.qqData.url = url;
    if(_isStrNotNull(title))
    [UMSocialData defaultData].extConfig.qqData.title = title;
//    if(_isStrNotNull(url)){
//    [UMSocialData defaultData].extConfig.qqData.qqMessageType = UMSocialQQMessageTypeDefault;
//    }else{
        [UMSocialData defaultData].extConfig.qqData.qqMessageType = UMSocialQQMessageTypeDefault;
   // }
    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToQQ]
                                                        content:content
                                                          image:thumbImg
                                                       location:nil
                                                    urlResource:nil
                                            presentedController:nil completion:^(UMSocialResponseEntity *response){
                                                 if(!me.block)return;
        if (response.responseCode == UMSResponseCodeSuccess) {
            block(YES,nil);
        }else{
            block(NO,@"分享失败");
        }
    }];
}

- (void)share2Sina:(NSString *)content
               url:(NSString *)url
        controller:(UIViewController *)ctrl
      captureImage:(UIImage *)captureImage
           uiBlock:(void (^)(BOOL success,NSString *message) )block{
    self.block=block;
    
    [[UMSocialControllerService defaultControllerService] setShareText:[NSString stringWithFormat:@"%@ %@",_safeStr(content),_safeStr(url)]
     
     
                                                            shareImage:captureImage socialUIDelegate:self];        //设置分享内容和回调对象
  
    [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina].snsClickHandler(ctrl,[UMSocialControllerService defaultControllerService],YES);
    
    self.isSinaBind=YES;
    [[NSUserDefaults standardUserDefaults] setBool:self.isSinaBind forKey:@"isSinaBind"];

    
//    [UMSocialSnsService presentSnsIconSheetView:ctrl
//                                         appKey:@"5454f768fd98c555870082a1"
//                                      shareText:[NSString stringWithFormat:@"%@ %@",_safeStr(content),_safeStr(url)]
//                                     shareImage:captureImage
//                                shareToSnsNames:@[UMShareToSina]
//                                       delegate:self];
   
}

- (void)loginOutSinaBlock:(void (^)(BOOL success))block{
    [[UMSocialDataService defaultDataService] requestUnOauthWithType:UMShareToSina
                                                          completion:^(UMSocialResponseEntity *response) {
                                                              
                                                              if(response.responseCode == UMSResponseCodeSuccess){
                                                                  self.isSinaBind=NO;
                                                                  [[NSUserDefaults standardUserDefaults] setBool:self.isSinaBind forKey:@"isSinaBind"];
                                                              }
                                                              
                                                              if(block){
                                                                 
                                                                  block(response.responseCode == UMSResponseCodeSuccess);
                                                              }
                                                          }];
}

- (void)loginInSinaBlock:(void (^)(BOOL success))block{
    
    UMSocialSnsPlatform *snsPlatform = [UMSocialSnsPlatformManager getSocialPlatformWithName:UMShareToSina];
   
    snsPlatform.loginClickHandler(nil,[UMSocialControllerService defaultControllerService],YES,^(UMSocialResponseEntity *response){
        
        if(response.responseCode == UMSResponseCodeSuccess){
            self.isSinaBind=YES;
            [[NSUserDefaults standardUserDefaults] setBool:self.isSinaBind forKey:@"isSinaBind"];
        }
        
        if(block){
            
            block(response.responseCode == UMSResponseCodeSuccess);
        }
        
        
    });

    
    
    
    [[UMSocialDataService defaultDataService] requestBindToSnsWithType:UMShareToSina
                                                            completion:^(UMSocialResponseEntity *response) {
                                                                
                                                                if(response.responseCode == UMSResponseCodeSuccess){
                                                                    self.isSinaBind=YES;
                                                                    [[NSUserDefaults standardUserDefaults] setBool:self.isSinaBind forKey:@"isSinaBind"];
                                                                }
                                                                
                                                                if(block){
                                                                    
                                                                    block(response.responseCode == UMSResponseCodeSuccess);
                                                                }
                                                            }];
}

//实现回调方法（可选）：
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{

    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        self.isSinaBind=YES;
        [[NSUserDefaults standardUserDefaults] setBool:self.isSinaBind forKey:@"isSinaBind"];
        if(self.block)
        self.block(YES,nil);
    }else{
        if(self.block)
        self.block(YES,@"分享失败");
    }
}

-(void)didCloseUIViewController:(UMSViewControllerType)fromViewControllerType{
   
}

-(void)onReq:(BaseReq*)req{
    
    
}


-(void)onResp:(BaseResp*)resp{
    if([resp isKindOfClass:[SendMessageToWXResp class]]){
         if(!self.block)return;
        if(resp.errCode==WXSuccess){
            self.block(YES,nil);
        }else{
            self.block(NO,@"分享失败");
        }
    }
    self.block=nil;
   // NSLog(@"---%@",resp);
}

- (void)registPush{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
    if(UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
    {
        //register remoteNotification types
        UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
        action1.identifier = @"action1_identifier";
        action1.title=@"Accept";
        action1.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序
        
        UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];  //第二按钮
        action2.identifier = @"action2_identifier";
        action2.title=@"Reject";
        action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序，在后台处理
        action2.authenticationRequired = YES;//需要解锁才能处理，如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略；
        action2.destructive = YES;
        
        UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init];
        categorys.identifier = @"category1";//这组动作的唯一标示
        [categorys setActions:@[action1,action2] forContext:(UIUserNotificationActionContextDefault)];
        
        UIUserNotificationSettings *userSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert
                                                                                     categories:[NSSet setWithObject:categorys]];
        [UMessage registerRemoteNotificationAndUserNotificationSettings:userSettings];
        
    } else{
        //register remoteNotification types
        [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
         |UIRemoteNotificationTypeSound
         |UIRemoteNotificationTypeAlert];
    }
#else
    //register remoteNotification types
    [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
     |UIRemoteNotificationTypeSound
     |UIRemoteNotificationTypeAlert];
#endif
    
    //for log
    [UMessage setLogEnabled:YES];
    self.isNotPush=NO;

}

- (void)unRegistPush{
    [UMessage unregisterForRemoteNotifications];
    self.isNotPush=YES;
}

- (void)updateMenu{
    [self getWithUrl:@"http://appv2.chanlin.org/e/app/cate.php" param:nil dataBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {
       // NSString *status=[responseObj sgrFGetStringForKey:@"status"];
        //NSArray *array=[responseObj sgrGetArrayForKey:@"0"];
        if(success && [responseObj isKindOfClass:[NSArray class]]){
            NSArray *array=(NSArray *)responseObj;
          
             NSMutableDictionary *menus=[NSMutableDictionary dictionary];
            NSMutableArray *mArray=[NSMutableArray array];
            for(NSDictionary *dic in array){
               
                NSMutableDictionary *menu=[NSMutableDictionary dictionary];
                [menu sgrSetObject:[dic sgrGetStringForKey:@"classid"] forKey:@"channelId"];
                [menu sgrSetObject:[dic sgrGetStringForKey:@"classname"] forKey:@"channelName"];
                [menu sgrSetObject:[dic sgrGetStringForKey:@"url"] forKey:@"url"];
                [menu sgrSetObject:[dic sgrFGetStringForKey:@"tpl"] forKey:@"tpl"];
                [menus sgrSetObject:menu forKey:[dic sgrGetStringForKey:@"classid"]];
                [mArray sgrAddObject:[dic sgrGetStringForKey:@"classid"]];
            }
            
            [[NSUserDefaults standardUserDefaults] setObject:menus forKey:menus_dic];
            [[NSUserDefaults standardUserDefaults] setObject:mArray forKey:menus_order];
            [[CLGloble sharedInstance] reflash];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            
        }
        
    } uiBlock:^(BOOL success, id responseObj, NSError *message, NSMutableDictionary *param) {
        
    }];
}

@end
